/**
 *  提供两个接口：
 *    1. 轮询查询任务消息
 *    2. 接收消息查询请求，处理消息队列
 */

var request = require('request');

var messageList = {};  ////{task_id1:{msg1,isCompleted,err},task_id2:{msg2,isCompleted,err},...}

var getMessage = function (url, cb) {
    var timer = setInterval(function () {
        request(url, function (err, response, data) {
            var dataJson = JSON.parse(data);
            if (dataJson.data.data.isCompleted) {
                clearInterval(timer);
            }
            cb(dataJson.data.data);
        });
    }, 200);

};

var handleMessage = function (req, res, next) {
    var task_id = req.params.task_id;
    var msg = messageList[task_id];
    if (msg) {
        res.format_json({data: msg}, 200, null);
    } else {
        res.format_json(null, 400, "cannot get msg of task: " + task_id);
    }
};

var setMessage = function (task_id, msg) {
    messageList[task_id] = msg;
};

exports.getMessage = getMessage;
exports.handleMessage = handleMessage;
exports.setMessage = setMessage;


